package communication.listeners;

import java.sql.SQLException;
import java.sql.Statement;

import server.Server;
import server.ServerCommunicator;
import message.InsertDataRequestMessage;
import message.InsertDataResponseMessage;
import message.Message;
import message.ServerMessageWrapper;
import communication.MessageListener;
import communication.MessageReceivedEvent;

public class InsertDataListener implements MessageListener
{
	private final ServerCommunicator communicator;
	
	public InsertDataListener(ServerCommunicator communicator)
	{
		this.communicator = communicator;
	}
	private boolean insertData(String username, String password)
	{
		boolean success = false;
		
		java.sql.Connection dbConnection = Server.getDatabaseConnection();
		
		if (dbConnection != null)
		{
			try
			{
				Statement statement = dbConnection.createStatement();
				statement.execute("INSERT INTO users (username, password, creationTime) VALUES ('" + username + "', '" + password + "', NOW())");
			
				success = true;
			}
			catch (SQLException e) {}
			
			try
			{
				dbConnection.close();
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			}
		}
		
		return success;
	}
	@Override
	public void messageRecieved(MessageReceivedEvent e)
	{
		ServerMessageWrapper message = ((ServerMessageWrapper) e.getMessage());
		InsertDataRequestMessage innerMessage = (InsertDataRequestMessage) message.internalMessage;
		InsertDataResponseMessage response = new InsertDataResponseMessage();
		
		response.setSuccess(insertData(innerMessage.getUsername(), innerMessage.getPassword()));
		
		communicator.sendMessage(message.connectionId, response);
	}

	@Override
	public boolean acceptsMessage(Message message)
	{
		if (message.getClass().equals(ServerMessageWrapper.class))
			message = ((ServerMessageWrapper) message).internalMessage;
		
		return message.getClass().equals(InsertDataRequestMessage.class);
	}
}
